/**
 * FourColumnFileInput - Reads in an input file that has 4 items formated as 
 * <item name>, <item mass>,<price per unit mass>, <number of items>.
 * 
 * CS575 Software Design
 * Group 6
 * Group Members: Anthony Davidson, Kendra Scheesley, Lyndsey Whitman, Stephen Zakrewsky
 * Date: May 19, 2012
 * Main Author(s): Anthony Davidson
 * 
 * Modified: 6/1 Stephen Zakrewsky
 */

package edu.drexel.cs575.a3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FourColumnFileInput implements UserInputCollector
{
	private Scanner	scanner;

	FourColumnFileInput(String filename) throws FileNotFoundException
	{
		scanner = new Scanner(new File(filename));
	}

	public boolean hasNextItem()
	{
		if (this.scanner == null)
		{
			return false;
		}

		return scanner.hasNextLine();
	}

	public WeighableItem getNextItem()
	{
		if (!this.hasNextItem())
		{
			throw new IllegalStateException("No items available");
		}

		String itemLine = this.scanner.nextLine();
		String[] itemArray = itemLine.split(",");

		WeighableItem weighableItem = null;

		if (itemArray.length == 4)
		{
			// For the purposes of this assignment we'll assume the data in the
			// text
			// file is formatted correctly.
			WeighableItems composite = new WeighableItems(itemArray[0]);

			for (int i = 0; i < Double.parseDouble(itemArray[3]); i++)
			{
				WeighableItem leaf = new SingleWeighableItem(itemArray[0],
						                                     Double.parseDouble(itemArray[1]),
						                                     Double.parseDouble(itemArray[2]));
				composite.add(leaf);
			}

			weighableItem = composite;
		}
		else
		{
			throw new IllegalStateException(
					"File Format incorrect. File must contain 4 items comma separated.\n"
							+ "Example: <item name>, <item mass>,<price per unit mass>, <number of items>");

		}

		return weighableItem;
	}
}
